package com.woniuxy.health.aspect;

import com.woniuxy.health.manager.service.IOperationLogService;
import com.woniuxy.health.model.manager.OperationLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Arrays;

@Aspect
@Component
@Order(1)
public class OperationLogAspect {

    @Autowired
    private IOperationLogService operationLogService;

    @Autowired
    private HttpServletRequest request;

    @Pointcut("execution(* * ..*Controller.*(..))")
    public void logPointcut() {
    }

    @AfterReturning(returning = "result", pointcut = "logPointcut()")
    public void saveOperationLog(JoinPoint joinPoint, Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取操作日志注解
        OperationLogAnnotation annotation = method.getAnnotation(OperationLogAnnotation.class);
        if (annotation != null) {
            OperationLog operationLog = new OperationLog();

            // 设置操作日志属性
            operationLog.setOperAccount(getOperAccount()); // 获取操作账号
            //operationLog.setNickName(getNickName()); // 获取用户名
            operationLog.setNickName(getOperAccount()); // 获取用户名
            operationLog.setOperTime(new Timestamp(System.currentTimeMillis())); // 设置操作时间
            operationLog.setOperIp(getIpAddress()); // 获取操作人IP地址
            operationLog.setOperUri(getRequestUri()); // 获取请求URL
            operationLog.setOperMethodName(method.getName()); // 设置操作方法名称
            operationLog.setOperRequParam(getRequestParameters(joinPoint)); // 获取请求参数
            //operationLog.setOperRespParam(getResponseParameters(result)); // 获取返回结果
            operationLog.setOperModul(annotation.module()); // 设置操作模块
            operationLog.setOperType(annotation.type()); // 设置操作类型
            operationLog.setOperDesc(annotation.description()); // 设置操作描述
            operationLog.setState((byte) 1); // 设置操作结果
            try {
                // 保存操作日志
                operationLogService.save(operationLog);
            } catch (Exception e) {
                // 记录操作失败的日志
                OperationLog errorLog = new OperationLog();
                errorLog.setOperAccount(getOperAccount());
                //errorLog.setNickName(getNickName());
                errorLog.setNickName(getOperAccount());
                errorLog.setOperTime(new Timestamp(System.currentTimeMillis()));
                errorLog.setOperIp(getIpAddress());
                errorLog.setOperUri(getRequestUri());
                errorLog.setOperMethodName(method.getName());
                errorLog.setOperRequParam(getRequestParameters(joinPoint));
                errorLog.setOperModul(annotation.module());
                errorLog.setOperType(annotation.type());
                errorLog.setOperDesc("操作失败：" + annotation.description()); // 在操作描述前添加"操作失败："前缀
                errorLog.setState((byte) 0); // 设置操作结果为失败

                // 保存操作失败的日志
                operationLogService.save(errorLog);
            }
        }
    }

    // 获取操作账号
    private String getOperAccount() {
        // 从会话中获取account
        //String operAccount = (String) request.getSession().getAttribute("account");
        String operAccount = (String) ManagerThreadLocalData.get("account");
        return operAccount;
    }

    // 获取用户名
    private String getNickName() {
        // 从会话中获取nickName
        //String nickName = (String) request.getSession().getAttribute("nickName");
        String nickName = (String) ManagerThreadLocalData.get("nickName");
        return nickName;
    }

    // 获取操作人IP地址
    private String getIpAddress() {
        // 实现获取操作人IP地址的逻辑
        String ipAddress = request.getRemoteAddr();
        return ipAddress;
    }

    // 获取请求URL
    private String getRequestUri() {
        // 实现获取请求URL的逻辑
        String requestUri = request.getRequestURI();
        return requestUri;
    }

    // 获取请求参数
    private String getRequestParameters(JoinPoint joinPoint) {
        // 实现获取请求参数的逻辑
        Object[] args = joinPoint.getArgs();
        String requestParams = Arrays.toString(args);
        return requestParams;
    }

    // 获取返回结果
   /* private String getResponseParameters(Object result) {
        // 实现获取返回结果的逻辑
        String responseParams = result.toString();
        return responseParams;
    }*/
}
